//
//  InviteViewController.m
//  Growth
//
//  Created by 洪波 陈 on 5/17/12.
//  Copyright (c) 2012 MEETStudio. All rights reserved.
//

#import "InviteViewController.h"

#import "ContactsViewController.h"
#import "SelInviteViewController.h"

#import "SDImageView+SDWebCache.h"

#import "FriendInviteCellView.h"

#import "PersonalViewController.h"

#define kRecommendSectionTitle @"推荐好友"

static WebConnectionArray *userSearch_connection;
static WebConnectionArray *userRecommend_connection;
static WebConnectionArray *inviteFriend_connection;

static UserDataType userDataType = kUserDataNone;
static int inviteSectionIndex = -1;

@interface InviteViewController ()

@end



@implementation InviteViewController


@synthesize mytabelView;

@synthesize invitedFriendsDict;

@synthesize tableSections;
@synthesize dataSourceDict;

@synthesize friendsSearchArray;
@synthesize  savedSearchTerm, savedScopeButtonIndex, searchWasActive;


- (void)dealloc
{
    //CLog(@"InviteView released! self retain count %d", [self retainCount]);
    [mytabelView release];
    
    [tableSections release];
    [dataSourceDict release];
    
    [friendsSearchArray release];
    
    
    if (userSearch_connection != nil) {
        
        userSearch_connection.connectionDelegate = nil;
        [userSearch_connection release];
        userSearch_connection = nil;
    }
    
    if (userRecommend_connection != nil) {
        
        userRecommend_connection.connectionDelegate = nil;
        [userRecommend_connection release];
        userRecommend_connection = nil;
    }
    
    if (inviteFriend_connection != nil) {
        inviteFriend_connection.connectionDelegate = nil;
        [inviteFriend_connection release];
        inviteFriend_connection = nil;
    }
    
    self.searchDisplayController.delegate = nil;
    
    //CLog(@"InviteView released! self retain count %d", [self retainCount]);

    [super dealloc];
    CLog(@"InviteView released!");
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    userDataType = kUserDataNone;
    inviteSectionIndex = -1;
    
    // Do any additional setup after loading the view from its nib.
    
    //定义返回按钮
    UIBarButtonItem * backBarButtonItem=[[UIBarButtonItem alloc] initWithTitle: @"返回" style:UIBarButtonSystemItemDone target:self action: nil];   
    
    [[self navigationItem] setBackBarButtonItem:backBarButtonItem];  
    [backBarButtonItem release];
    
    self.navigationItem.title = @"添加好友";
    
    [self loadTableData];
    
    

    
    
    //Search 功能
    friendsSearchArray = [[NSMutableArray alloc] init];
    // restore search settings if they were saved in didReceiveMemoryWarning.
    if (self.savedSearchTerm)
	{
        [self.searchDisplayController setActive:self.searchWasActive];
        [self.searchDisplayController.searchBar setSelectedScopeButtonIndex:self.savedScopeButtonIndex];
        [self.searchDisplayController.searchBar setText:savedSearchTerm];
        
        self.savedSearchTerm = nil;
    }
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    
    friendsSearchArray = nil;
}

- (void)viewDidDisappear:(BOOL)animated
{
    // save the state of the search UI so that it can be restored if the view is re-created
    self.searchWasActive = [self.searchDisplayController isActive];
    self.savedSearchTerm = [self.searchDisplayController.searchBar text];
    self.savedScopeButtonIndex = [self.searchDisplayController.searchBar selectedScopeButtonIndex];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}



#pragma mark Load Data
- (void)loadTableData
{
    if (invitedFriendsDict == nil) {
        invitedFriendsDict = [[NSMutableDictionary alloc] init];
    }
    
    if (tableSections== nil) {
        tableSections = [[NSMutableArray alloc] init];  
    }
    if (dataSourceDict == nil) {
        dataSourceDict = [[NSMutableDictionary alloc] init];
    }
    
    
    //邀请好友
    [tableSections addObject:@"联系人"];
    
    //邀请/被邀请
    [tableSections addObject:@"邀请"];
    
    //推荐好友
    [tableSections addObject:kRecommendSectionTitle];
    
    [self loadRecommendUserData];

}

- (void)loadRecommendUserData
{
    if (NETWORK_STATUS_UNLOADING) {
        int uid = [[[NSUserDefaults standardUserDefaults]valueForKey:@"userId"] intValue];
        
        NSMutableURLRequest *request = [WebRequest recommendFriendsWith:uid pageNo:1 pageSize:30];
        
        CLog(@"request %@", request);
        
        
        userDataType = kRecommendUser;
        if (userRecommend_connection != nil) {
            userRecommend_connection.connectionDelegate = nil;
        }
        userRecommend_connection = [[WebConnectionArray alloc] initWith:request delegate:self dataBaseListName:nil];
    }
    else{
        [LoadingView showImage:[UIImage imageNamed:@"wangluo_iphone.png"] info:@"哎呀，网络好像有问题，无法获取推荐好友！" duration:DEFAULT_LOADING_TIME *1.2];
    }
    
    

}

#pragma mark -
#pragma mark WebConnection Delegate
- (void)connectionSuccess:(NSDictionary *)dict
{
    CLog(@"dict, %@", dict);

   
}

- (void)connectionArraySuccess:(NSDictionary *)dict  connectionURL:(NSString *)url
{
    CLog(@"dict, %@", dict);
    
    [LoadingView hideWithAnimated:NO];
    
    //推荐
    NSRange range = [url rangeOfString:@"recommend"];
    if (range.length > 0) {
        //推荐好友
        NSArray *array = [dict objectForKey:@"object"];
        
        if ([array count] >0) {
            NSMutableArray * friendsArray = [dataSourceDict objectForKey:kRecommendSectionTitle];
            if (friendsArray == nil) {
                friendsArray = [[NSMutableArray alloc] init];
                [dataSourceDict setObject:friendsArray forKey:kRecommendSectionTitle];
                [friendsArray release];
            }
            
            [friendsArray addObjectsFromArray:array];
        }
        
        [self.mytabelView reloadData];
        
        userDataType = kUserDataNone;
        
        return;
    }

    //搜索
    range = [url rangeOfString:@"search"];
    if (range.length > 0) {
        [friendsSearchArray removeAllObjects];
        
        NSArray *array = [dict objectForKey:@"object"];
        
        if ([array count] >0) {

            [friendsSearchArray addObjectsFromArray:array];
            
        }

        [self.searchDisplayController.searchResultsTableView reloadData];
        
        userDataType = kUserDataNone;
        
        return;
    }
    
    //添加好友
    range = [url rangeOfString:@"invite"];
    if (range.length >0) {
        NSString *objectStr = [dict objectForKey:@"object"];
        
        if (objectStr) {
            BOOL isSuccess = [objectStr boolValue];
            
            if (userDataType != kUserDataNone) {
                if (isSuccess) {
                    switch (userDataType) {
                        case kSearchUser:
                        {
                            [LoadingView showDurationMessageLoadingViewWith:kDefaultTipsLoadingDuration message:@"邀请成功！"];
                            CLog(@"index %d", inviteSectionIndex);
                            if (friendsSearchArray != nil) {
                                //删除
                                //                if (inviteSectionIndex <[friendsSearchArray count]) {
                                //                    [friendsSearchArray removeObjectAtIndex:inviteSectionIndex];
                                //                }
                                //                [self.searchDisplayController.searchResultsTableView reloadData];
                                
                                
                                //修改标记
                                NSDictionary *dict = [friendsSearchArray objectAtIndex:inviteSectionIndex];
                                
                                NSString *userId = [dict objectForKey:@"userId"];
                                NSString *isAdd = [invitedFriendsDict objectForKey:userId];
                                if (isAdd == nil){
                                    [invitedFriendsDict setObject:@"YES" forKey:userId];
                                }
                                
                                
                                [self.searchDisplayController.searchResultsTableView reloadData];
                                
                            }
                            
                            break;
                        }
                        case kRecommendUser:
                        {
                            [LoadingView showDurationMessageLoadingViewWith:kDefaultTipsLoadingDuration message:@"邀请成功！"];
                            //删除记录
                            NSMutableArray * friendsArray = [dataSourceDict objectForKey:kRecommendSectionTitle];
                            //                
                            //            if (friendsArray != nil) {
                            //                [friendsArray removeObjectAtIndex:inviteSectionIndex];
                            //            }
                            //            [self.mytabelView reloadData];
                            
                            //修改标记
                            NSDictionary *dict = [friendsArray objectAtIndex:inviteSectionIndex];
                            
                            NSString *userId = [dict objectForKey:@"userId"];
                            NSString *isAdd = [invitedFriendsDict objectForKey:userId];
                            if (isAdd == nil){
                                [invitedFriendsDict setObject:@"YES" forKey:userId];
                            }            
                            [self.mytabelView reloadData];
                            
                            break;
                        }
                        default:
                            break;
                    }
                }
                else {
                    [LoadingView showDurationMessageLoadingViewWith:kDefaultTipsLoadingDuration message:@"操作失败！"];
                }
                
                
                userDataType = kUserDataNone;
                inviteSectionIndex = -1;
            }
        }

        return;
    }
    
    

}

- (void)connectionError:(NSError *)error
{
    CLog(@"dict %@", error);
    [LoadingView hideWithAnimated:NO];
    if (userDataType == kSearchUser || userDataType == kRecommendUser) {
        [LoadingView showDurationMessageLoadingViewWith:kDefaultTipsLoadingDuration message:@"邀请失败，请重试！"];
        
        userDataType = kUserDataNone;
        inviteSectionIndex = -1;
    }
}

- (void)connectionArrayError:(NSError *)error
{
    CLog(@"connectionArrayError");
    
    [LoadingView hideWithAnimated:NO];
}

- (void)postSuccess:(NSString *)postinfo
{
    
}


#pragma mark -
#pragma mark UITableViewDelegate and UITableViewDatasource methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (tableView == self.searchDisplayController.searchResultsTableView)
    {
        return 1;
    }
    else {
        return [self.tableSections count];

    }
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (tableView == self.searchDisplayController.searchResultsTableView)
    {
        return [friendsSearchArray count];
    }
    else {
        return [self numberOfRowsInSection:section];
    }
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSInteger section = indexPath.section;
    NSInteger row = indexPath.row;
    
    
    NSArray *array;
    
    if (tableView == self.searchDisplayController.searchResultsTableView) {
        array = friendsSearchArray;
    }
    else {
        NSString *key = [tableSections objectAtIndex:section];
        array = [dataSourceDict objectForKey:key];
    }
    
//    if (array == nil || row > [array count]) {
//        return nil;
//    }
    
    static NSString *MyIdentifier = @"FriendInviteCellView";
	// Try to retrieve from the table view a now-unused cell with the given identifier.
	FriendInviteCellView *cell =(FriendInviteCellView *) [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
	
    if (cell == nil) {
		NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"FriendInviteCellView" 
                                                     owner:self options:nil];
#ifdef __IPHONE_2_1
		cell = (FriendInviteCellView *)[nib objectAtIndex:0];
#else
		cell = (FriendInviteCellView *)[nib objectAtIndex:1];
#endif
        
        cell.imageView.layer.cornerRadius =3;
        cell.imageView.clipsToBounds = YES;
        
        UIButton *button = cell.actionButton;
        [button addTarget:self action:@selector(addFriendsAction:) forControlEvents:UIControlEventTouchUpInside];
        button.tag = row;

        UILabel *addLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, -2, CGRectGetWidth(button.frame), CGRectGetHeight(button.frame))];
        [addLabel setTextAlignment:UITextAlignmentCenter];
        [addLabel setFont:[UIFont systemFontOfSize:14]];
        [addLabel setText:@"添加"];
        addLabel.tag = 110;
        addLabel.font = [UIFont boldSystemFontOfSize:14];
        [addLabel setBackgroundColor:[UIColor clearColor]];
        [button addSubview:addLabel];
        
        //个人主页
        UIButton *userButton = cell.imageAction;
        userButton.tag = row;
        [userButton addTarget:self action:@selector(toUserViewAction:) forControlEvents:UIControlEventTouchUpInside];
	}
    
    for (UIView *subView in [cell subviews]) {
        subView.tag = row;
    }
    
    NSDictionary *dict = [array objectAtIndex:row];
    
    cell.titleLabel.text = [dict objectForKey:@"userNickname"];
    
    
    //ICON
    if(![[dict objectForKey:@"userAttachmentId"] isMemberOfClass:[NSNull class]]){
        
        NSString *string=[NSString stringWithFormat:@"%@%@/%@/100x100",UCENTERBASEURL,@"/gravatar",[dict objectForKey:@"userAttachmentId"]];
        NSURL *url = [NSURL URLWithString:string];	
        [cell.imageView setImageWithURL:url refreshCache:NO placeholderImage:[UIImage imageNamed:@"geren_set_iphone.png"] imageType:kImageCache_Content_Icon];
	}
   	
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    [cell setSelected:NO];
    
    cell.tag = row;
    
    
    //如果已经邀请隐藏添加按钮，显示标记
    NSString *userId = [dict objectForKey:@"userId"];
    NSString *isAdd = [invitedFriendsDict objectForKey:userId];
    if (isAdd && [isAdd isEqualToString:@"YES"]) {
        cell.actionButton.hidden = YES;
        cell.tipsImageView.hidden = NO;
    }
    else {
        cell.actionButton.hidden = NO;
        cell.tipsImageView.hidden = YES;
    }
    
	return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
	return cell.frame.size.height;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (tableView == self.searchDisplayController.searchResultsTableView) {
        return 0;
    }
    else {
        return 50;
    }
    
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    if (tableView == self.searchDisplayController.searchResultsTableView) {
        return nil;
    }
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.tag = section;
    
    [button addTarget:self action:@selector(headerClicked:) forControlEvents:UIControlEventTouchUpInside];
    
    CGFloat size = 14;
    CGFloat width = [[self.tableSections objectAtIndex:section] sizeWithFont:[UIFont boldSystemFontOfSize:size]].width;
    while(width > 300){
        size -= 1.0;
        width = [[self.tableSections objectAtIndex:section] sizeWithFont:[UIFont boldSystemFontOfSize:--size]].width;
    }
    
    if (section == 2) {
        
        [button setBackgroundImage:[UIImage imageNamed:@"barbg_friend1_iphone.png"] forState:UIControlStateNormal];
        
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, 300, 50)];
        [label setBackgroundColor:[UIColor clearColor]];
        label.textColor = [UIColor blackColor];
        label.font = [UIFont boldSystemFontOfSize:14];
        
        NSString *titleStr = [self.tableSections objectAtIndex:section];
        label.text = titleStr;
        [label setTextAlignment:UITextAlignmentLeft];
        [button addSubview:label];
        [label release];
        
        [button setUserInteractionEnabled:NO];
    }
    else {
        
        UIImageView *image = [[UIImageView alloc] initWithFrame:CGRectMake(281, 12, 25, 25)];
        image.image = [UIImage imageNamed:@"icon_jiantou_iphone.png"];
        [button addSubview:image];
        [image release];
        
        [button setBackgroundColor:[UIColor colorWithRed:235.0/255.0 green:223.0/255.0 blue:207.0/255 alpha:1.0]];
        
        UILabel *labelTitle = [[UILabel alloc] initWithFrame:CGRectMake(50,7, 300, 20)];
        [labelTitle setBackgroundColor:[UIColor clearColor]];
        labelTitle.textColor = [UIColor blackColor];
        labelTitle.font = [UIFont boldSystemFontOfSize:14];
        [labelTitle setTextAlignment:UITextAlignmentLeft];
        
        NSString *titleStr = [self.tableSections objectAtIndex:section];
        labelTitle.text = titleStr;
        [button addSubview:labelTitle];
        [labelTitle release];
        
        
        UILabel *labelDetail = [[UILabel alloc] initWithFrame:CGRectMake(50, 27, 300, 15)];
        [labelDetail setBackgroundColor:[UIColor clearColor]];
        labelDetail.textColor = [UIColor grayColor];
        labelDetail.font = [UIFont boldSystemFontOfSize:12];
        [labelDetail setTextAlignment:UITextAlignmentLeft];
        
        UIImageView *iconImageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 10, 30, 30)];
        
        
        switch (section) {
            case 0:
            {
                iconImageView.image = [UIImage imageNamed:@"lianxiren_friend1_iphone.png"];
                
                labelDetail.text = @"从您的联系人中添加好友";
                break;
            }
            case 1:
            {
                iconImageView.image = [UIImage imageNamed:@"letter_friend1_iphone.png"];
                
                labelDetail.text = @"通过邮件或短信邀请您的好友加入印象宝贝";
                break;
            }
            default:
                break;
        }
        
        [button addSubview:iconImageView];
        
        [button addSubview:labelDetail];
        [labelDetail release];

    }
    

    
    
    button.layer.shadowOffset =CGSizeMake(0, 1);
    button.layer.shadowColor = [[UIColor blackColor] CGColor];
    button.layer.shadowOpacity = 0.7;
    
    
    return button;
}



#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    cell.highlighted = NO;
    cell.selectedBackgroundView.backgroundColor = [UIColor clearColor];
    
}


-(void)headerClicked:(id)sender{
    UIButton *button = (UIButton *)sender;
    
    NSInteger section = button.tag;
    switch (section) {
        case 0:
        {
            [LoadingView showDefaultLoadingView];

            CLog(@"nav go");
            
            ContactsViewController *content = [[ContactsViewController alloc] init] ;

            [self.navigationController pushViewController:content animated:YES];
            
            [content release];
            //[LoadingView hideWithAnimated:YES];
            CLog(@"通讯录");
            break;
        }
        case 1:
        {

            SelInviteViewController *content = [[SelInviteViewController alloc] init];

            [self.navigationController pushViewController:content animated:YES];
            
            [content release];
            
            CLog(@"自定义短信/邮件");
            break;
        } 
        default:
            break;
    }
    
}

-(int)numberOfRowsInSection:(NSInteger)section{
    
    NSString *key = [tableSections objectAtIndex:section];
    
    NSArray *array = [dataSourceDict objectForKey:key];
    
    if (array != nil) {
        return [array count];
    }
    else {
        return 0;
    } 
    
    
}


#pragma mark -
#pragma mark UISearchDisplayController Delegate Methods

- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
//    [self filterContentForSearchText:searchString scope:
//     [[self.searchDisplayController.searchBar scopeButtonTitles] objectAtIndex:[self.searchDisplayController.searchBar selectedScopeButtonIndex]]];
    
    // Return YES to cause the search result table view to be reloaded.
    CLog(@"shouldReloadTableForSearchString");
    
    return YES;
}


- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchScope:(NSInteger)searchOption
{
//    [self filterContentForSearchText:[self.searchDisplayController.searchBar text] scope:
//     [[self.searchDisplayController.searchBar scopeButtonTitles] objectAtIndex:searchOption]];
    
    // Return YES to cause the search result table view to be reloaded.
    CLog(@"shouldReloadTableForSearchScope");
    return YES;
}


- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    
    [self filterContentForSearchText:[self.searchDisplayController.searchBar text] scope:nil];
    CLog(@"searchBarSearchButtonClicked");
}

#pragma mark -
#pragma mark Content Filtering

- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{
	/*
	 Update the filtered array based on the search text and scope.
	 */
    
    CLog(@"scope %@", scope);
    
    if (NETWORK_STATUS_UNLOADING) {
        int uid = [[[NSUserDefaults standardUserDefaults]valueForKey:@"userId"] intValue];
        
        NSMutableURLRequest *request = [WebRequest userSearchWith:uid keyWord:searchText pageNo:1 pageSize:30];
        
        CLog(@"request %@", request);
        
        userDataType = kSearchUser;
        if (userSearch_connection != nil) {
            userSearch_connection.connectionDelegate = nil;
        }
        userSearch_connection = [[WebConnectionArray alloc] initWith:request delegate:self dataBaseListName:nil];
        
        
    }

}

#pragma mark -
#pragma mark Action


- (void)toUserViewAction:(id)sender
{
    UIButton *button = (UIButton *)sender;
    
    int index = button.tag;
    
    CLog(@"Frined Index %d", index);
    
    NSDictionary *dict;
    
    if (self.searchDisplayController.isActive) {
        
        dict = [friendsSearchArray objectAtIndex:index];
    }
    else {
        NSString *key = [tableSections lastObject];
        NSMutableArray *array = [dataSourceDict objectForKey:key];
        
        dict = [array objectAtIndex:index];
    }
    
    int fuid = [[dict objectForKey:@"userId"] intValue];

    
    PersonalViewController *personalViewController = [[PersonalViewController alloc] initWithUserId:fuid];
    
    [self.navigationController pushViewController:personalViewController animated:YES];
    
    [personalViewController release];
    
}

- (void)addFriendsAction:(id)sender
{
    
    
    if (NETWORK_STATUS_LOADING) {
        UIButton *button = (UIButton *)sender;
        
        int index = button.tag;
        
        CLog(@"Add frineds Index %d", index);
        
        NSDictionary *dict;
        
        if (self.searchDisplayController.isActive) {
            
            dict = [friendsSearchArray objectAtIndex:index];
            userDataType = kSearchUser;
        }
        else {
            NSString *key = [tableSections lastObject];
            NSMutableArray *array = [dataSourceDict objectForKey:key];
            
            dict = [array objectAtIndex:index];
            userDataType = kRecommendUser;
        }
        
        NSString *uidStr = [[NSUserDefaults standardUserDefaults]valueForKey:@"userId"];
        NSString *fuidStr = [dict objectForKey:@"userId"];
        
        NSMutableURLRequest *request = [WebRequest inviteFriendWith:[uidStr intValue] fuid:[fuidStr intValue]];
        
        CLog(@"request %@", request);
        
        
        
        inviteSectionIndex = index;
        
        [LoadingView showDefaultLoadingView];
        if (inviteFriend_connection != nil) {
            inviteFriend_connection.connectionDelegate = nil;
        }
        inviteFriend_connection = [[WebConnectionArray alloc] initWith:request delegate:self dataBaseListName:nil];
        
    }

}

#pragma mark textField delegate
-(void)textFieldDidBeginEditing:(UITextField *)textField{
    
    textField.text = @"";
    [textField setTextColor:[UIColor darkGrayColor]];
    
}

-(NSString *)changeStringFommat:(NSString *)str{
    
    if ([str isMemberOfClass:[NSNull class]]) {
        return @"";
    }
    
    
    NSString *string;
    if (![str isMemberOfClass:[NSNull class]]) {
        
        string = [str stringByReplacingOccurrencesOfString:@"<br>" withString:@"\n"]; 
    }
    if (![string isMemberOfClass:[NSNull class]]) {
        string = [string stringByReplacingOccurrencesOfString:@"&nbsp;" withString:@" "];
    }
    
    return string;
    
}


-(IBAction)beforBackHome:(id)sender{
    [self.view removeFromSuperview];
}

@end
